package com.snow.auth.service;

import com.snow.auth.entity.SystemUser;
import com.snow.auth.entity.WechatUserEntity;
import com.snow.auth.repository.SystemUserRepository;
import com.snow.auth.repository.WechatUserRepository;
import com.snow.exception.CommonRuntimeException;
import com.snow.jpa.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class WechatUserService extends BaseService<WechatUserRepository, WechatUserEntity, Integer> {

    private final SystemUserRepository systemUserRepository;

    public WechatUserService(WechatUserRepository repository, SystemUserRepository systemUserRepository) {
        super(repository);
        this.systemUserRepository = systemUserRepository;
    }

    @Transactional(rollbackFor = Exception.class)
    public void linkSystemUser(WechatUserEntity params) {
        WechatUserEntity entity = get(params.getId());
        if (entity == null) {
            throw new CommonRuntimeException("用户信息不存在，请稍后再试");
        }
        SystemUser systemUser = systemUserRepository.findById(params.getUserId()).orElseThrow(() -> new CommonRuntimeException("用户信息不存在，请稍后再试"));
        entity.setUserId(systemUser.getId());
        save(entity);
        systemUser.setOpenId(entity.getOpenId());
        systemUserRepository.save(systemUser);
    }

    @Transactional(rollbackFor = Exception.class)
    public void unlinkSystemUser(Integer id) {
        WechatUserEntity entity = get(id);
        if (entity == null) {
            throw new CommonRuntimeException("用户信息不存在，请稍后再试");
        }
        SystemUser systemUser = systemUserRepository.findById(entity.getUserId()).orElse(null);
        if (systemUser != null) {
            systemUser.setOpenId(null);
            systemUserRepository.save(systemUser);
        }
        entity.setUserId(null);
        save(entity);
    }
}
